//
// Created by zerax on 2020/10/23.
//

#include <glad/glad.h>
#include "game.hh"

#include "config.hh"

bool Game::init() {
    if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        return false;
    }
    m_running = true;

    m_lastTime = SDL_GetTicks();

    m_window = SDL_CreateWindow(APP_NAME,
                                SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
                                APP_WINDOW_WIDTH, APP_WINDOW_HEIGHT,
                                SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

    m_glContext = SDL_GL_CreateContext(m_window);

    if (SDL_GL_MakeCurrent(m_window, m_glContext) < 0) {
        return false;
    }

    if (!gladLoadGLLoader(SDL_GL_GetProcAddress)) {
        return false;
    }


    return true;
}

void Game::run() {
    SDL_Event e;
    while (m_running) {
        while (SDL_PollEvent(&e)) {
            if (e.type == SDL_QUIT) {
                m_running = false;
            } else if (e.type == SDL_MOUSEBUTTONDOWN) {
                if (m_onMouseClick) m_onMouseClick(0);
            }
        }

        auto currentTime = SDL_GetTicks();
        m_deltaTime = float(currentTime - m_lastTime) / 1000.0f;
        m_lastTime = currentTime;

        update();

        SDL_GL_SwapWindow(m_window);
    }
}

void Game::wrapMouseInWindow(int x, int y) {
    SDL_WarpMouseInWindow(m_window, x, y);
}

float Game::getDeltaTime() {
    return m_deltaTime;
}

void Game::setOnMouseClick(Game::OnMouseClickCallback&& onMouseClick) {
    m_onMouseClick = onMouseClick;
}

int Game::getScreenWidth() const {
    int w;
    SDL_GetWindowSize(m_window, &w, nullptr);
    return w;
}

int Game::getScreenHeight() const {
    int h;
    SDL_GetWindowSize(m_window, nullptr, &h);
    return h;
}
